<template>
  <div class="main">
    <!-- <van-sticky> -->
      <div class="nav">
        <img :src="back" alt="" @click="handleBack"/>
        <div class="title">{{ title }}检测人</div>
        <div class="del" v-if="userInfos.id && userInfos.testId != 0" @click="del">删除</div>
      </div>
      <!-- </van-sticky> -->
      <div class="tx">
<!--        @click="changeImg()"-->
        <div class="avatar"
             :style="{backgroundImage: `url(${userInfos.avatar ? store.state.imgUrl + userInfos.avatar : logo})`,'background-size':'100%'}">
        </div>
        <!-- <van-image class="avatar" :src="userInfos.avatar ? store.state.imgUrl + userInfos.avatar : logo"
                 round
      /> -->
      </div>
    
    <div class="body">
       <van-form ref="form">
      <van-cell
          title="手机号"
          :is-link="this.$route.query.name == '新增' && !userInfos.phone  ? true : false" 
          @click="handlePhone"
          :value="userInfos.phone ? userInfos.phone : '点击添加手机号'"/>
      <van-field
          v-model="userInfos.name"
          label="姓名"
          placeholder="请输入姓名"
          input-align="right"/>
      <van-cell title="性别" :value="userInfos.sexName?userInfos.sexName:'点击选择性别'" @click="showSex = true" is-link/>
      <van-cell title="出生日期" is-link :value="userInfos.birthday?userInfos.birthday:'点击选择出生日期'"
                @click="showDatePicker = true"/>
      <van-cell title="年龄" :value="String(userInfos.age) ? userInfos.age + '岁':'请选择出生日期'"/>
      <van-field
          v-model="userInfos.height"
          label="身高"
          placeholder="请输入身高"
          input-align="right"
          type="digit"
          maxlength="3">
        <template #extra>
          <span class="unit">CM</span>
        </template>
      </van-field>
      <van-field
          v-model.trim="userInfos.weight"
            label="体重"
            name="体重"
            placeholder="请输入体重"
            input-align="right"
            type="number"
            autocomplete="off"
            :rules="[{ validator:weightP }]">
        <template #extra>
          <span class="unit">KG</span>
        </template>
      </van-field>
      <van-cell title="BMI" :value="userInfos.bmi ? userInfos.bmi : '0.0' "/>
      <van-cell title="吸烟" is-link :value="userInfos.smokingName" @click="showSmoking = true"/>
      <div class="footer">
        <div class="size" @click="save">保存</div>
      </div>
    </van-form>
    </div>
    <van-action-sheet v-model="showSex" :actions="sexActions" cancel-text="取消" @select="onSelect"/>
    <van-action-sheet v-model="showSmoking" :actions="smokingActions" cancel-text="取消" @select="onSelectSmoking"/>
    <van-action-sheet v-model="showRelation" :actions="relationList" cancel-text="取消"
                      @select="onSelectRelation"/>
    <van-popup v-model="showDatePicker" position="bottom">
      <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="getDateTime"
          @cancel="showDatePicker = false"/>
    </van-popup>
  </div>
</template>

<script>
import {dateFormat} from "@/utils/date.js";
import {deleteTester, getFriendList, getGenderList, getSmokingList, modifyUserBy, newTester,getTesterById} from "../../../api/my";
import store from '../../../store'
import {mapState} from "vuex";
import {Dialog} from 'vant';
export default {
  name: "personInfo",
  data() {
    return {
      store: store,
      title: '',
      showSmoking: false,
      smokingActions: [],
      showSex: false,
      sexActions: [],
      showDatePicker: false,
      currentDate: new Date(),
      minDate: new Date(1880, 0, 1),
      maxDate: new Date(),
      back: require("@/assets/my/back.png"),
      setImg: require("@/assets/my/set-icon.png"),
      userInfos: {
        avatar: '',
        nickName: '', //昵称
        name: '', //姓名
        sex: '',//0男 1女 2未知
        sexName: '',
        birthday: '',//生日
        age: '',
        height: '',
        weight: '',
        bmi: '',//BMI = 体重（千克） / (身高（米） × 身高（米）)
        isSmoking: '',// 0频繁 1偶尔 3不抽烟
        smokingName: '',
        friendLabel: '',
        label: '',
        phone:''
      },
      relationList: [],
      showRelation: false,
      logo: require("@/assets/tx.png"),
      queryId:''
    }
  },
  computed: {
    ...mapState(['userInfo']),
  },
  created() {
    window["getInfoFromFlutter"] = (info) => {
      if (JSON.parse(info).action === 'upload') {
        // this.$toast(info)
        this.getInfoFromFlutter(info)
      }
    };
  },
  async mounted() {
    this.storeUser = 
    this.$route.query.name === '新增' ? this.title = '新增' : this.title = '编辑'
    if (this.title === '编辑') {

      // 1、通过id查询当前检测人信息
      // if (this.$route.query.id) {
      //   console.log('id',this.$route.query.id)
      //   this.getUserInfo(this.$route.query.id)
      // }

      // 2、通过路由跳转传递过来的当前检测人信息
      this.userInfos = JSON.parse(this.$route.query.obj)
      this.userInfos.age = this.getBrithAge(new Date(this.userInfos.birthday))
      // this.userInfos.phone = this.$route.query.phone ? this.$route.query.phone : ''
    }else if (this.title === '新增'){
      if (this.$route.query.addUserInfo) {
         this.userInfos = JSON.parse(this.$route.query.addUserInfo)
        this.userInfos.age = this.getBrithAge(new Date(this.userInfos.birthday))
        console.log('新增检测人获取到的检测人信息', this.userInfos)
      }
     
      
    }

    //调用字典 获取关系 是否吸烟 性别
    let relations = await this.getRelation();//关系
    relations.forEach((item, index) => {
      let obj = {
        name: item.label,
        value: item.value
      }
      this.relationList.push(obj)
    })
    let smokings = await this.getSmoking();// 吸烟
    smokings.forEach((item, index) => {
      let obj = {
        name: item.label,
        value: item.value
      }
      this.smokingActions.push(obj)
    })
    let sexs = await this.getSex();//性别
    sexs.forEach((item, index) => {
      let obj = {
        name: item.label,
        value: item.value
      }
      this.sexActions.push(obj)
    })
    if (this.title === '编辑' || this.title === '新增') {
      this.sexActions.map((item, index) => {
        if (item.value == this.userInfos.sex) {
          this.userInfos.sexName = item.name
        }
      })
      this.smokingActions.map((item, index) => {
        if (item.value == this.userInfos.isSmoking) {
          this.userInfos.smokingName = item.name
        }
      })
    }
  },
  watch: {
    'userInfos.weight': {
      handler(newVal, oldVal) {
        console.log('监听到数据变化');
        this.calculateBMI()
      },
      deep: true
    },
    'userInfos.height': {
      handler(newVal, oldVal) {
        console.log('监听到数据变化');
        this.calculateBMI()
      },
      deep: true
    }
  },
  methods: {
    getInfoFromFlutter(info) {
      let data = JSON.parse(info);
      if (data.param.type == "image") {
        if (data.param.images && data.param.images.length > 0) {
          // this.imageList = data.param.images;
          this.userInfo.avatar = data.param.images[0]
        }
      }
    },
    getUserInfo(id){
      let data = {
        id: id
      }
       getTesterById(data).then(res => {
          console.log(res)
       })
    },
    getSex() {
      return new Promise((resolve, reject) => {
        getGenderList().then(res => {
          resolve(res.data)
        })
      })
    },
    getSmoking() {
      return new Promise((resolve, reject) => {
        getSmokingList().then(res => {
          resolve(res.data)
        })
      })
    },
    getRelation() {
      return new Promise((resolve, reject) => {
        getFriendList().then(res => {
          resolve(res.data)
        })
      })
    },
    getDateTime() {
      this.userInfos.birthday = dateFormat(
          new Date(this.currentDate),
          "yyyy-MM-dd"
      );
      this.userInfos.age = this.getBrithAge(new Date(this.currentDate));
      this.showDatePicker = false;
    },
    calculateBMI() {
      console.log('calc')
      if (this.userInfos.height && this.userInfos.weight) {
        const heightInMeter = this.userInfos.height / 100; // 将身高从cm转换为m
        const bmi = this.userInfos.weight / (heightInMeter * heightInMeter); // 计算BMI
        this.userInfos.bmi = bmi.toFixed(2); // 保留两位小数
      }
    },
    getBrithAge(birthday) {
      var nowDay = new Date();
      //出生年月日
      var birthYear = birthday.getFullYear();
      var birthMonth = birthday.getMonth() + 1;
      var birthDate = birthday.getDate();
      //当前年月日
      var nowYear = nowDay.getFullYear();
      var nowMonth = nowDay.getMonth() + 1;
      var nowDate = nowDay.getDate();

      //计算年差
      var age = nowYear - birthYear;
      //当前月大于出生月，则岁数不足
      if (nowMonth < birthMonth) {
        age = age - 1;
      } else if (nowMonth == birthMonth) {
        if (nowDate < birthDate) {
          age = age - 1;
        }
      }
      return age;
    },
    onSelect(item) {
      this.userInfos.sexName = item.name
      this.userInfos.sex = item.value
      this.showSex = false
    },
    onSelectSmoking(item) {
      this.userInfos.smokingName = item.name
      this.userInfos.isSmoking = item.value
      this.showSmoking = false
    },
    onSelectRelation(item) {
      this.userInfos.friendLabel = item.value
      this.userInfos.label = item.name
      this.showRelation = false
    },
    handleBack() {
      this.$router.push(
        {
          path: '/detectorManagement',
          query: {}
        }
       )
      // this.$router.go(-1);
    },
    changeImg() {
      let message = {
        action: "upload",
        param: {
          type: "image", //必填
          callback: 1,
        },
      };
      getInfoFromVue.postMessage(JSON.stringify(message));
      console.log('app切换头像')
    },
    del() {
       Dialog.confirm({
        title: '提示',
        message: '您确定要删除该检测人吗？',
        confirmButtonColor: 'rgba(242, 150, 0, 1)'
      }).then(() => {
        let data = {
          id: this.userInfos.id
        }
      deleteTester(data).then(res => {
        if (res.success) {
          this.$toast.success('删除成功')
          this.$router.push(
            {
              path: '/detectorManagement',
              query: {}
            }
         )
        }
      })
      }).catch(err => {

      })
     
    },
    save() {
      if (this.weightP(String(this.userInfos.weight)) && this.userInfos.phone   && this.userInfos.name && this.userInfos.sexName && this.userInfo.birthday && this.userInfo.height && this.userInfo.smokingName ) {
            if (this.userInfos.id) {
               const addForm = {//修改时表单需要提交的参数
                id:this.userInfos.id,
                inspectorUserId:this.userInfos.inspectorUserId,
                name:this.userInfos.name,
                sex:this.userInfos.sex,
                avatar:this.userInfos.avatar,
                birthday:this.userInfos.birthday,
                height:this.userInfos.height,
                weight:this.userInfos.weight,
                isSmoking:this.userInfos.isSmoking
              }
              // 编辑保存接口
              modifyUserBy(addForm).then(res => {
                if (res.success) {
                  this.$toast.success('修改成功')
                  this.handleBack()
                }
              })
            } else {
              //新增
              const addForm = {//新增时表单需要提交的参数
                inspectorUserId:this.userInfos.userId,
                name:this.userInfos.name,
                sex:this.userInfos.sex,
                avatar:this.userInfos.avatar,
                birthday:this.userInfos.birthday,
                height:this.userInfos.height,
                weight:this.userInfos.weight,
                isSmoking:this.userInfos.isSmoking
              }
              // 新增保存接口
              newTester(addForm).then(res => {
                if (res.success) {
                  this.$toast.success('新增成功')
                   this.handleBack()
                }
              })
            }
      }else{
        this.testValueAll()
      }
      
    },
    // 校验每个参数不能为空
    testValueAll(){
      if (this.userInfos.phone == '' || this.userInfos.phone == null || this.userInfos.phone == undefined ) {
          this.$toast('手机号不能为空')
        } 
        else 
        if(this.userInfos.name == '' || this.userInfos.name == null || this.userInfos.name == undefined ){
          this.$toast('姓名不能为空')
        } else if (this.userInfos.sexName == '' || this.userInfos.sexName == null || this.userInfos.sexName == undefined ) {
          this.$toast('性别不能为空')
        } else if (this.userInfos.birthday == ''  || this.userInfos.birthday == null || this.userInfos.birthday == undefined) {
          this.$toast('出生日期不能为空')
        } else if (this.userInfos.height == '' || this.userInfos.height == null || this.userInfos.height == undefined) {
          this.$toast('身高不能为空')
        } else if (this.userInfos.weight == '' || this.userInfos.weight == null || this.userInfos.weight == undefined) {
          this.$toast('体重不能为空')
        } else if (!this.weightP(String(this.userInfos.weight))) {
          this.$toast('体重请保留两位小数')
        } else if (this.userInfos.smokingName == '' || this.userInfos.smokingName == null || this.userInfos.smokingName == undefined) {
          this.$toast('请选择吸烟情况')
        }
    },
     // 体重校验
    weightP(v){
      if (v) {
        return /^[0-9]+(\.[0-9]{1,2})?$/.test(v) 
      }
    },
    // 添加手机号
    handlePhone(){
      if (this.$route.query.name == '新增' && this.userInfos.phone == '' ) {
        this.$router.push(
        {
          path: '/addPhone',
          query: {}
        }
       )
       
      }
    }
  }
}
</script>

<style scoped lang="less">
.main {
  height: 100vh;
  // padding: 0px 15px;

  
  .nav {
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    .title{
      font-size: 20px;
      font-weight: 500;
    }

    > img {
      width: 10px;
      height: 16px;
      position: absolute;
      left: 15px;
    }

    .del {
      position: absolute;
      right: 15px;
      font-size: 17px;
      font-weight: 400;
      line-height: 20.27px;
    }
  }

  .tx {
    display: flex;
    justify-content: center;
    padding-top: 14px;

    .avatar {
      border: 1px solid #ebeef5;
      background-repeat: no-repeat;
      background-size: 100%;
      width: 89px;
      height: 89px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      background: rgba(0, 0, 0, 0.8);
      opacity: 1;
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;

      > img {
        width: 41px;
        height: 41px;
      }

    }

  }

  .change-avatar {
    font-size: 12px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 17.38px;
    color: rgba(84, 84, 84, 1);
    text-align: center;
    margin-top: 5px;
    background-repeat: no-repeat;
    background-size: 100%;
  }

  .footer {
    display: flex;
    justify-content: center;
    margin-top: auto;
    align-items: center;
    // margin-bottom: 15px;
    margin: 100px auto;

    .size {
      width: 141px;
      height: 38px;
      //opacity: 1;
      border-radius: 19px;
      background: rgba(242, 150, 0, 1);
      font-size: 23px;
      font-weight: 500;
      //line-height: 38px;
      color: rgba(255, 255, 255, 1);
      //text-align: center;
      //vertical-align: top;
      display:flex;
      justify-content: center;
      align-items: center;
      padding: 3px;
    }


  }

  /deep/.van-cell {
      font-size: 17px;
      //  padding: 15px 16px;
  } 
   /deep/ .van-action-sheet__name {
    font-size: 20px;
  }
  /deep/ .van-picker-column__item {
    font-size: 20px;
  }
  /deep/ .van-picker__confirm {
    font-size: 20px;
  }
  /deep/ .van-picker__cancel{
    font-size: 20px;
  }
  /deep/ .van-ellipsis{
    font-size: 20px;
  }
 

}
</style>
